var fsd_config = new FSD_CONFIG();//配置
var api = frameElement.api, W = api.opener;
var js=document.scripts;
var jsPath;
for(var i=js.length;i>0;i--){
    if(js[i-1].src.indexOf("fsd.all.js")>-1){
        jsPath=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/")+1);
    }
}



var jsondata = eval('('+api.data+')');
var qtrootpath = jsondata.path;
var autoname = jsondata.autoName;
var createDateFolder = jsondata.createDateFolder;
var fileType = jsondata.fileType;
$(document).ready(function(){
	
	

	$("#nowfilepath").val(qtrootpath);
	//var api = frameElement.api;
	//$("#jsonurl").val(api.data);
	
    getAjaxJson(1 , 1 , '');
	
	$('#showtype').change(function(){
		var type= $(this).children('option:selected').val();
		getAjaxJson('1' ,type , $("#nowfilepath").val());
	});
	
	$("#returnup").click(function(){
		var uppath = $("#previouspath").val();
		$("#nowfilepath").val(uppath);
		if(uppath != null && uppath != ""){
			var type = $("#showtype").val();
			getAjaxJson('1' ,type , uppath);
		}
	});
	
	$("#uploadbutton").click(function(){
	    var fsdfilemanager = new FsdFileManager();
	    fsdfilemanager.rootpath = $("#nowfilepath").val();
	    fsdfilemanager.autoName = autoname;
	    fsdfilemanager.fileType = fileType;
   	    fsdfilemanager.getUploadDialog_me(createDateFolder  , null , function(){
   	        var type = $("#showtype").val();
		    getAjaxJson('1' ,type , $("#nowfilepath").val());
   	    });
	});
	
	$("#makefolder").click(function(){
		W.$.dialog({
			id: 'foldercreate',
			title:'新建文件夹',
		    content: 'url:'+ jsPath +'dialogs/foldercreate/folder_create.html',
		    data: $("#nowfilepath").val(),
		    max: false,
		    min: false,
		    resize: false,//是否允许改变大小
		    lock: true,//锁屏
		    fixed: true,//位置静止
		    self:true,
		    width: '300px',
		    height: '50px',
		    button: [
		             {
			            name: '确认',
			            callback: function(){
			                var nowpath = $("#nowfilepath").val();
			                var rootpath = $("#rootpath").val();
			                var newfolder = api.get('foldercreate').document.getElementById('newfoldername').value;
			                newfolder = encodeURI(newfolder);
			                newfolder = encodeURI(newfolder);
			                if(newfolder != null && newfolder != ""){
			                	var url = jsPath +  fsd_config.imageManagerUrl + "?qtrootpath=" +  qtrootpath + "&nowpath=" + nowpath + "&rootpath="+rootpath+"&operattype="+3+"&nowtime=" + generateMixed(5)+"&newfolder="+newfolder;
				                $.ajax({
				                    type: "get",//使用get方法访问后台
				                    dataType: "json",//返回json格式的数据
				                    url: url ,//要访问的后台地址
				                    success: function(msg){//msg为返回的数据，在这里做数据绑定
					                   	var jsondata = eval(msg);
					                   	alert(jsondata.message);
				                    },
				                    error: function(msg){
				                    	var jsondata = eval(msg);
				                   	 	alert(jsondata.message);
				                    }
				           	 	});
			                }else{
			                	alert("目录名称不得为空");
			                }
			                
			                return false;
			            },
			            focus: true
	        },
		        {
		            name: '关闭'
		        }
		    ],
		    close: function(){
		    	var type = $("#showtype").val();
		    	getAjaxJson('1' ,type , $("#nowfilepath").val());
		    }
		});
	});
});

/*Ajax访问得到数据json*/
function getAjaxJson(operattype ,type ,path){
	var url = jsPath + fsd_config.imageManagerUrl + "?qtrootpath=" +  qtrootpath + "&nowpath=" + path + "&showtype="+type+"&operattype="+operattype+"&nowtime=" + generateMixed(5);
	 $.ajax({
         type: "get",//使用get方法访问后台
         dataType: "json",//返回json格式的数据
         url: url ,//要访问的后台地址
         success: function(msg){//msg为返回的数据，在这里做数据绑定
        	 var jsondata = eval(msg);
        	 if(operattype == "1"){
        		 $("#nowfilepath").val(jsondata.rootpath);
        		 $("#previouspath").val(jsondata.previouspath);
        		 $("#rootpath").val(jsondata.rootpath);
            	 var html = "";
            	 if(type == 1){
            		 html = makeImgTable(jsondata);
            	 }else if(type == 2){
            		 html = makeInfoTable(jsondata);
            	 }
            	 $("#testtest").empty();
            	 $(html).appendTo("#testtest");
            	 setListener();
        	 }else if(operattype == "2"){
        		 var npwpath = $("#nowfilepath").val();
     			 getAjaxJson('1' ,type , npwpath);
     			 alert(jsondata.message);
        	 }
         }
	 });
}

/**
 * 创建缩略图
 * @param jsondata
 * @returns {String}
 */
function makeImgTable(jsondata){
	var html = "";
	 html += "<table>";
	 var ff = 0;
	 for(var i = 0; i < jsondata.filelist.length; i++){
		 if(ff==0){
			 html+="<tr>";
		 }
		 ff++;
		 	html+="<td>";
		 		html+="<div class=\"imagediv\">";
		 			html+="<img id='"+jsondata.filelist[i].filename+"' filetype='"+jsondata.filelist[i].filetype+"' filepath='"+jsondata.filelist[i].filepath+"' shortfilepath='"+jsondata.filelist[i].shortfilepath+"' alt='"+jsondata.filelist[i].filename+"' src='"+jsondata.filelist[i].imagepath+"'>";
		 		html+="</div>";
		 		html+="<div class=\"titilediv\">";
		 			html+=jsondata.filelist[i].filename;
		 		html+="</div>";
		 	html+="</td>";
		 	
		 	if(ff==5){
		 		html+="</tr>";
		 		ff=0;
		 	}
		
	 }
	 html += "</table>";
	 return html;
}

/**
 * 创建详细信息
 * @param jsondata
 * @returns {String}
 */
function makeInfoTable(jsondata){
	var html = "";
	html += "<table>";
	for(var i = 0; i < jsondata.filelist.length; i++){
		html += "<tr class=\"infotr\" id='"+jsondata.filelist[i].filename+"' filepath='"+jsondata.filelist[i].filepath+"' shortfilepath='"+jsondata.filelist[i].shortfilepath+"' filetype='"+jsondata.filelist[i].filetype+"' >";
			html += "<td width=\"70%\">";
				html += "<img width=\"16\" height=\"16\" align=\"absmiddle\" style=\"margin-right:5px;\" src='"+jsondata.filelist[i].imagepath+"' />";
				html += jsondata.filelist[i].filename;
			html += "</td>";
			
			html += "<td width=\"10%\">";
				html += jsondata.filelist[i].filesize;
			html += "</td>";
			
			html += "<td width=\"20%\">";
				html += jsondata.filelist[i].datetime;
			html += "</td>";
		html += "</tr>";
	}
	html += "</table>";
	return html;
}

var _time = null;

function setListener(){
	//图片右键删除--缩略图
	$(".contentdiv img").contextMenu({
		menuId: 'contextMenu',
		onContextMenuItemSelected:function(menuItemId, $triggerElement){
			if(window.confirm('你确定要删除吗？')){
				var type = $("#showtype").val();
				var nowpath = $triggerElement.attr('filepath');
				var filetype = $triggerElement.attr('filetype');
				if(filetype == "1"){
					nowpath = nowpath + $triggerElement.attr('id');
				}
				getAjaxJson('2' ,type , nowpath);
			}
			
		},
		onContextMenuShow:function($triggerElement){
						
		},
		showShadow:false
	});
	//图片右键删除--详细信息
	$(".contentdiv .infotr").contextMenu({
		menuId: 'contextMenu',
		onContextMenuItemSelected:function(menuItemId, $triggerElement){
			if(window.confirm('你确定要删除吗？')){
				var type = $("#showtype").val();
				var nowpath = $triggerElement.attr('filepath');
				var filetype = $triggerElement.attr('filetype');
				if(filetype == "1"){
					nowpath = nowpath + $triggerElement.attr('id');
				}
				getAjaxJson('2' ,type , nowpath);
			}
		},
		onContextMenuShow:function($triggerElement){
						
		},
		showShadow:false
	});
	
	//双击选中图片--缩略图
	$(".contentdiv img").dblclick(function(){
	    clearTimeout(_time);
		var filename = this.id;
		var shortfilename = $(this).attr("shortfilepath");
		var fullfilepath = $(this).attr("filepath");
		var filetype = $(this).attr("filetype");
		if(filetype == 1){
			var type = $("#showtype").val();
			var filepath = $(this).attr("filepath");
			$("#nowfilepath").val(filepath + filename + "/");
			getAjaxJson('1' ,type , filepath + filename + "/");
		}else if(filetype == 2){
			$("#resultfile").val(filename);
			$("#shortresultfile").val(shortfilename);
			$("#fullfilepath").val(fullfilepath);
			var api = frameElement.api, W = api.opener;
			api.close();
		}
		
	});
	
	//单击选中图片--缩略图
	$(".contentdiv img").click(function(){
	    var me = this;
	    clearTimeout(_time);
        _time = setTimeout(function(){
            if($("#showyuantu").attr("checked")==true){
                var filetype = $(me).attr("filetype");
                if(filetype == 2){
                    var filepath = $(me).attr("filepath");
                    var fsdfilemanager = new FsdFileManager();
                    fsdfilemanager.setImgUrl = filepath;
   	                fsdfilemanager.getImgviewDialog();
                }
	        }
        }, 200);
	});
	
	//双击选中图片--详细信息
	$(".contentdiv .infotr").dblclick(function(){
	    clearTimeout(_time);
		var filename = this.id;
		var shortfilename = $(this).attr("shortfilepath");
		var fullfilepath = $(this).attr("filepath");
		var filetype = $(this).attr("filetype");
		if(filetype == 1){
			var type = $("#showtype").val();
			var filepath = $(this).attr("filepath");
			$("#nowfilepath").val(filepath + filename + "/");
			getAjaxJson('1' ,type , filepath + filename + "/");
		}else if(filetype == 2){
			$("#resultfile").val(filename);
			$("#shortresultfile").val(shortfilename);
			$("#fullfilepath").val(fullfilepath);
			var api = frameElement.api, W = api.opener;
			api.close();
		}
	});
	
	//单击选中图片--详细信息
	$(".contentdiv .infotr").click(function(){
	    var me = this;
	    clearTimeout(_time);
        _time = setTimeout(function(){
            if($("#showyuantu").attr("checked")==true){
   	            var filetype = $(me).attr("filetype");
   	            if(filetype == 2){
   	                var filepath = $(me).attr("filepath");
   	                var fsdfilemanager = new FsdFileManager();
   	                fsdfilemanager.setImgUrl = filepath;
   	                fsdfilemanager.getImgviewDialog();
   	            }
   		    }
        }, 200);
	});
}

//获得随机字符串
function generateMixed(n) {
	var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random()*35);
        res += chars[id];
    }
    return res;
}